package com.sdjzu.wangfuying.disableautobrightness.service;

import android.content.Context;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Objects;

public class StatisticsServiceIsNotAService implements Serializable {
    private static transient StatisticsServiceIsNotAService _this = new StatisticsServiceIsNotAService();

    private final int[] mTimeSet = new int[100];
    private long lastPersistTimestamp = 0L;
    private boolean loaded = false;

    public static StatisticsServiceIsNotAService getInstance() {
        return _this;
    }

    private static File getCacheFile(Context context) {
        return new File(
                Objects.requireNonNull(context.getExternalCacheDir()).getAbsolutePath()
                        + File.separator
                        + "statistics.dat"
        );
    }

    public boolean isLoaded() {
        return loaded;
    }

    public long getLastPersistTimestamp() {
        return lastPersistTimestamp;
    }

    public synchronized void record(int timeInMs) {
        if (timeInMs >= 0 && timeInMs < mTimeSet.length)
            mTimeSet[timeInMs]++;
    }


    public int[] get() {
        return mTimeSet;
    }

    public synchronized boolean persist(Context context) {
        try {
            ObjectOutputStream oos = new ObjectOutputStream(
                    new FileOutputStream(
                            getCacheFile(context)
                    )
            );
            oos.writeObject(this);
            oos.close();
            lastPersistTimestamp = System.currentTimeMillis();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public synchronized boolean restore(Context context) {
        try {
            ObjectInputStream ois = new ObjectInputStream(
                    new FileInputStream(
                            getCacheFile(context)
                    )
            );
            StatisticsServiceIsNotAService._this = ((StatisticsServiceIsNotAService) ois.readObject());
            ois.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        loaded = true;
        return true;
    }
}
